from django.shortcuts import render, HttpResponse, redirect, reverse
from io import BytesIO
from django.contrib.auth import authenticate, login, logout

from xadmin.plugins.validcode import mkcode
from xadmin.plugins.auditlog import add_log
from xadmin.models import Sites

def validcode(request):
    img_obj, code = mkcode()
    request.session['pic_code'] = code
    request.session.set_expiry(3600*8)
    io_obj = BytesIO()
    img_obj.save(io_obj, 'png')
    data = io_obj.getvalue()
    return HttpResponse(data)


def dologin(request):
    if request.method == 'GET':
        return render(request, 'xadmin/login/index.html')
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        siteid = request.GET.get('siteid', '1')
        context = {
            'username': username,
            'password': password,
        }
        pic_code = request.POST.get('vcode')
        #print(pic_code)
        #print(request.session['pic_code'])
        scode = request.session.get('pic_code', None)
        if scode is None:
            context = {
                'error': '验证码已过期'
            }
            return render(request, 'xadmin/login/index.html', context)
        if pic_code.upper() == request.session['pic_code'].upper():
            #验证码正确
            user = authenticate(username=username, password=password)
            if user is not None:
                sites = Sites.objects.all()

                if user.is_staff == 1:
                    login(request, user)
                    if not sites:
                        return HttpResponse(
                            '<script>alert("你还没有任何站点，创建一个吧");window.location.href="/admin/site/add"</script>')
                    action = '用户 %s 登录了系统, 用户姓名：%s' % (user.username, user.chinese_name)
                    add_log(request, action, siteid)
                    return redirect(reverse('nodelist') + '?siteid=' + siteid)
                else:
                    context['error'] = '用户不允许登录此系统'
                    return render(request, 'xadmin/login/index.html', context)
            else:
                context['error'] = '用户名或密码错误'
                return render(request, 'xadmin/login/index.html', context)
        else:
            #验证码不正确
            context['error'] = '验证码不正确'
            return render(request, 'xadmin/login/index.html', context)


def dologout(request):
    logout(request)
    return redirect(reverse('dologin'))